<template>
  <div class="item-one" ref="itemOne">
    <div class="title">
      <span>渠道管理</span>
    </div>
    <div class="container">
      <div class="screeningBox">
        <div class="leftBox">
          <div class="leftitem">
            <div class="block">
              <el-date-picker
                v-model="month"
                type="month"
                @change="getNowMontht"
                placeholder="选择月"
              >
              </el-date-picker>
            </div>
            <el-select
              v-if="userinfo.rolesId != 5 && userinfo.rolesId != 6"
              v-model="channelType"
              placeholder="通道类型"
            >
              <el-option
                v-for="(item, index) in channelslist"
                :key="index"
                :label="item.options"
                :value="item.code"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div class="rightBox">
          <div class="rightitem" v-if="userinfo.rolesId != 5">
            <el-form ref="conditions" :model="conditions" label-width="80px">
              <el-autocomplete
                class="merchants"
                v-model.trim="tarminal.marid"
                @select="marid"
                :fetch-suggestions="searchMerchantsList"
                placeholder="商户名"
                :trigger-on-focus="false"
                @change="getMerchantId"
              ></el-autocomplete>
            </el-form>
          </div>
        </div>
      </div>
      <div class="screeningBox">
        <div class="leftBox" v-if="userinfo.rolesId != 4">
          <el-form ref="conditions" :model="conditions">
            <el-select
              v-if="
                userinfo.rolesId == 1 ||
                userinfo.rolesId == 8 ||
                userinfo.rolesId == 9
              "
              class="servicelevel"
              v-model="conditions.servicelevel"
              placeholder="服务商级别"
              @change="servicelevel"
            >
              <el-option keys="1" label="一级服务商" :value="1"></el-option>
              <el-option keys="2" label="二级服务商" :value="2"></el-option>
            </el-select>
            <el-autocomplete
              v-if="
                userinfo.rolesId == 1 ||
                userinfo.rolesId == 8 ||
                userinfo.rolesId == 2 ||
                userinfo.rolesId == 9
              "
              class="servicename"
              v-model.trim="conditions.servicename"
              :fetch-suggestions="querySearch"
              placeholder="服务商名称"
              @select="serviceid"
            ></el-autocomplete>
            <el-autocomplete
              v-if="userinfo.rolesId != 5"
              class="BDname"
              v-model.trim="conditions.BDname"
              :fetch-suggestions="BDname"
              placeholder="业务经理"
              @select="BDid"
            ></el-autocomplete>
          </el-form>
        </div>
        <div class="rightBox">
          <el-button
            icon="el-icon-search"
            type="primary"
            @click="searchTargetMonthInfo"
            >搜索</el-button
          >
          <el-button
            icon="el-icon-refresh"
            type="primary"
            @click="resetQuotaData"
            >重置</el-button
          >
        </div>
      </div>
    </div>
    <div class="tableBox">
      <el-table
        ref="multipleTable"
        :data="merchantarr"
        tooltip-effect="dark"
        style="width: 100%"
        stripe
        :header-cell-style="tableHeaderColor"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          align="center"
          type="index"
          label="序号"
        ></el-table-column>
        <el-table-column
          prop="channelname"
          align="center"
          label="通道名称"
        ></el-table-column>
        <el-table-column
          prop="status"
          align="center"
          label="通道状态"
        ></el-table-column>
        <el-table-column
          prop="type"
          align="center"
          label="通道类型"
        ></el-table-column>
        <el-table-column
          prop="createtime"
          align="center"
          label="通道入网时间"
        ></el-table-column>
        <el-table-column
          prop="instNo"
          align="center"
          label="服务商机构号"
        ></el-table-column>
        <el-table-column
          prop="isEntry"
          align="center"
          label="是否有进件接口"
        ></el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="modifyState(scope.row.merchantId)"
              >修改</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="combined"
          :current-page.sync="cur_page"
          @current-change="handleCurrentChange"
          @size-change="sizechange"
        ></el-pagination>
      </div>
    </div>
    <br />
    <br />
    <el-dialog
      title="修改是否有进件接口状态"
      :visible.sync="modifyStateDialog"
      width="30%"
      :before-close="handleClose"
    >
      <span>确定修改是否有进件接口状态</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyStateDialog = false">取 消</el-button>
        <el-button type="primary" @click="modifyStateDialog = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  APIgetQuotaStatisticsList,
  APIquotaStatistics,
  merchantlist,
  APIimportFile,
  dictionarylist,
  getservice,
  getBD,
} from "@/api/api";
import { number } from "echarts";
export default {
  name: "quotaPackageStatistics",
  data: function () {
    return {
      token: { token: sessionStorage.getItem("token") },
      modifyStateDialog: false,
      month: new Date(),
      type: "",
      channelType: "",
      exxxx: false,
      cur_page: 1,
      cur_size: 10,
      multipleSelection: [],
      visible: false,
      servicearr: [],
      merchantarr: [],
      combined: 10,
      pageCount: "",
      channelslist: [],
      datainfo: {
        quota: 0,
        availQuota: 0,
        residualQuota: 0,
      },
      tarminal: {
        payLogo: "",
        shopName: "",
        marid: "",
      },
      userinfo: "",
      date: "",
      loading: true,
      conditions: {
        servicelevel: "",
        servicename: "",
        stardate: "",
        enddate: "",
        serviceid: "",
        aisle: "",
        shopno: "",
        BDname: "",
        keywords: "",
      },
      dimension: "", //选择维度
      tagId: "",
    };
  },
  created() {
    this.userinfo = JSON.parse(sessionStorage.getItem("userInfo"));
    this.dictionarylist();

    this.getQuotaStatisticsList("1");

    this.getQuotaStatistics();
    if (this.userinfo.rolesId == 1) {
      this.conditions.servicelevel = 1;
      this.servicelevel("1");
      this.getQuotaStatistics("1");
    }
    if (this.userinfo.rolesId == 2) {
      this.conditions.servicelevel = 2;
      this.servicelevel("2");
      this.getQuotaStatistics("2");
    } else if (this.userinfo.rolesId == 3) {
      this.getBD(this.userinfo.fid);
    }
  },
  methods: {
    modifyState() {
      this.modifyStateDialog = true;
    },
    //批量更新额度包
    queryQuotaPackage() {
      console.log(11112);
    },
    // 获取所有通道type
    dictionarylist() {
      dictionarylist({ type: "channelType", status: 0 }).then((res) => {
        // console.log(res);
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
          this.channelslist = res.data;
        }
      });
    },
    successUploadQuota(res, file) {
      if (res.code == 405) {
        sessionStorage.removeItem("token");
        this.$router.push("/login");
      } else if (res.code == 200) {
        this.$message({
          message: "上传成功",
          type: "success",
        });
      } else {
        this.$message.error(res.message);
      }
    },
    //模糊查询商户名
    searchMerchantsList(queryString, cb) {
      let sosolist = {};
      sosolist = {
        page: 1,
        size: 20,
        merchantName: this.tarminal.marid,
      };
      merchantlist(sosolist).then((res) => {
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
          this.merchantarrlist = [];
          for (var i = 0; i < res.data.length; i++) {
            this.merchantarrlist.push({
              value: res.data[i].merchantName + " — " + res.data[i].merchantNo,
              id: res.data[i].id,
            });
          }
          let results = queryString
            ? this.merchantarrlist.filter(this.createFilter(queryString))
            : this.merchantarrlist;
          // 调用 callback 返回建议列表的数据
          cb(results);
        }
      });
    },
    getMerchantId(value) {
      if (value == "") {
        this.conditions.keywords = "";
      }
    },
    marid(item) {
      this.conditions.keywords = item.id;
      this.tarminal.shopName = "";
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !==
          -1
        );
      };
    },
    Permission_display(ids = []) {
      return ids.includes(this.userinfo.rolesId);
    },
    roundNumberProperties(array, properties) {
      for (let i = 0; i < array.length; i++) {
        let obj = array[i];
        for (let j = 0; j < properties.length; j++) {
          let property = properties[j];
          if (typeof obj[property] === "number") {
            obj[property] = (obj[property] / 100).toFixed(2);
          }
        }
      }
      return array;
    },
    // 额度包列表数据查询
    getQuotaStatisticsList(level) {
      let sosolist = {};
      if (level == 1) {
        sosolist = {
          page: this.cur_page,
          size: this.cur_size,
          merchantId: this.conditions.keywords,
          agent1Id: this.conditions.serviceid,
          channelType: this.channelType,
          bdId: this.conditions.BDid,
        };
      } else if (level == 2) {
        sosolist = {
          page: this.cur_page,
          size: this.cur_size,
          merchantId: this.conditions.keywords,
          agent2Id: this.conditions.serviceid,
          channelType: this.channelType,
          bdId: this.conditions.BDid,
        };
      }

      APIgetQuotaStatisticsList(sosolist).then((res) => {
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
          console.log("this.merchantarr =", res.data);
          let propertiesToRound = ["quota", "availQuota", "residualQuota"];
          this.merchantarr = this.roundNumberProperties(
            res.data,
            propertiesToRound
          );
          this.pageCount = res.pageInfo.pageCount;
          this.combined = res.pageInfo.recordCount;
          this.loading = false;
        }
      });
    },
    // 额度包统计（month）
    getQuotaStatistics(level, TargetMonth = "") {
      let currentMonth = new Date().getMonth() + 1;
      if (TargetMonth == currentMonth) TargetMonth = "";
      let checkStatisticaldata = {};
      if (level == 1) {
        checkStatisticaldata = {
          month: TargetMonth,
          merchantId: this.conditions.keywords,
          agent1Id: this.conditions.serviceid,
          channelType: this.channelType,
          bdId: this.conditions.BDid,
        };
      } else if (level == 2) {
        checkStatisticaldata = {
          month: TargetMonth,
          merchantId: this.conditions.keywords,
          agent2Id: this.conditions.serviceid,
          channelType: this.channelType,
          bdId: this.conditions.BDid,
        };
      }

      APIquotaStatistics(checkStatisticaldata).then((res) => {
        if (res.code != 200) {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error",
          });
        } else {
          if (res.data == null) {
            this.datainfo.quota = 0;
            this.datainfo.availQuota = 0;
            this.datainfo.residualQuota = 0;
          } else {
            // this.datainfo = res.data;
            this.datainfo.quota = (res.data.quota / 100).toFixed(2);
            this.datainfo.availQuota = (res.data.availQuota / 100).toFixed(2);
            this.datainfo.residualQuota = (
              res.data.residualQuota / 100
            ).toFixed(2);
          }
        }
      });
    },
    // 服务商级别
    servicelevel(val) {
      this.servicearr = [];
      getservice({
        type: val,
      }).then((res) => {
        for (var i = 0; i < res.data.rows.length; i++) {
          this.servicearr.push({
            value: res.data.rows[i].agentname,
            id: res.data.rows[i].id,
          });
        }
      });
    },
    // 服务商名称
    querySearch(queryString, cb) {
      let sosolist = {};
      sosolist = {
        page: 1,
        size: 20,
        type: this.conditions.servicelevel,
        keywords: this.conditions.servicename,
      };
      getservice(sosolist).then((res) => {
        // console.log(res);
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
          this.servicearr = [];
          for (var i = 0; i < res.data.rows.length; i++) {
            this.servicearr.push({
              value: res.data.rows[i].agentname,
              id: res.data.rows[i].id,
            });
          }
          let results = queryString
            ? this.servicearr.filter(this.createFilter(queryString))
            : this.servicearr;
          // 调用 callback 返回建议列表的数据
          cb(results);
        }
      });
    },
    BDid(item) {
      this.conditions.BDid = item.id;
    },
    serviceid(item) {
      this.conditions.serviceid = item.id;
      this.getBD(item.id);
    },
    getBD(id) {
      this.BDarr = [];
      getBD({ agentid: id }).then((res) => {
        console.log(res);
        for (var i = 0; i < res.data.rows.length; i++) {
          this.BDarr.push({
            value: res.data.rows[i].name,
            id: res.data.rows[i].id,
          });
        }
      });
    },
    // 业务经理
    BDname(queryString, cb) {
      let BDarr = this.BDarr;
      let results = queryString
        ? BDarr.filter(this.createFilter(queryString))
        : BDarr;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    //搜索
    searchTargetMonthInfo() {
      this.loading = true;
      this.cur_page = 1;
      if (!this.conditions.servicename) {
        this.conditions.serviceid = "";
      }
      if (!this.conditions.BDname) {
        this.conditions.BDid = "";
      }
      if (this.month.getMonth() + 1 != new Date().getMonth() + 1) {
        if (this.conditions.servicelevel == 1) {
          this.getQuotaStatistics("1", this.month.getMonth() + 1);
          this.merchantarr = [];
        } else if (this.conditions.servicelevel == 2) {
          this.getQuotaStatistics("2", this.month.getMonth() + 1);
          this.merchantarr = [];
        } else {
          this.getQuotaStatistics("2", this.month.getMonth() + 1);
          this.merchantarr = [];
        }
        // this.getQuotaStatistics(this.month.getMonth() + 1);
        // this.merchantarr=[]
      } else {
        if (this.conditions.servicelevel == 1) {
          this.getQuotaStatisticsList("1");
          this.getQuotaStatistics("1", this.month.getMonth() + 1);
        } else if (this.conditions.servicelevel == 2) {
          this.getQuotaStatisticsList("2");
          this.getQuotaStatistics("2", this.month.getMonth() + 1);
        } else {
          this.getQuotaStatisticsList("2");
          this.getQuotaStatistics("2", this.month.getMonth() + 1);
        }
      }
    },
    // 分页导航
    handleCurrentChange(val) {
      if (this.conditions.servicelevel == 1) {
        this.getQuotaStatisticsList("1");
      } else if (this.conditions.servicelevel == 2) {
        this.getQuotaStatisticsList("2");
      } else {
        this.getQuotaStatisticsList("2");
      }

      this.cur_page = val;
      this.$nextTick(() => {
        document.querySelectorAll(".content")[0].scrollTop = "0";
      });
    },
    // 分页数量
    sizechange(val) {
      this.cur_size = val;
      if (this.conditions.servicelevel == 1) {
        this.getQuotaStatisticsList("1");
      } else if (this.conditions.servicelevel == 2) {
        this.getQuotaStatisticsList("2");
      } else {
        this.getQuotaStatisticsList("2");
      }
      this.$nextTick(() => {
        document.querySelectorAll(".content")[0].scrollTop = "0";
      });
    },
    //重置搜索条件
    resetQuotaData() {
      this.channelType = "";
      this.conditions.servicename = "";
      this.conditions.serviceid = "";
      this.conditions.servicelevel = "";
      this.conditions.BDname = "";
      this.conditions.BDid = "";
      this.month = new Date();
      this.tarminal.marid = "";
      this.conditions.keywords = "";
      if (this.userinfo.rolesId == 2) {
        this.conditions.servicelevel = 2;
      }
    },
  },
};
</script>

<style scoped lang='less'>
.buttonStyle {
  display: flex;
}
.upload-demo /deep/ .el-upload--text {
  border: 1px dashed #fff;
}
.queryQuota {
  margin-right: 20px;
  width: 115px;
  height: 35px;
}
.upload-demo /deep/ .el-upload--text {
  width: 71px;
  height: 35px;
}
.title {
  background: #fff;
  padding: 10px 10px;
  font-size: 18px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
}
.name {
  width: 25%;
}
.screeningBox {
  width: 100%;
  display: flex;
}
.leftBox,
.rightBox {
  width: 50%;
  padding: 0 15px;
  box-sizing: border-box;
}
.leftBox > .leftitem {
  margin-bottom: 15px;
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.rightBox > .rightitem {
  margin-bottom: 15px;
}
.merchants {
  width: 50%;
}
.tableBox {
  margin-top: 20px;
}
.servicename {
  width: 43%;
}
.servicename1 {
  width: 60%;
}
.servicelevel {
  width: 23.5%;
}
.width20 {
  width: 20%;
}
.red {
  color: #f9607d;
}
.blue {
  color: #01aaef;
}
.stitle {
  padding: 5px 0;
  font-size: 18px;
}
.statistical {
  width: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
  background: #00152a;
  color: #fff;
  padding: 12px;
  box-sizing: border-box;
  .statisticalitem {
    flex: 1;
    text-align: center;
    border-right: 1px solid rgba(255, 255, 255, 0.445);
    font-size: 13px;
    line-height: 180%;
    &:nth-last-child(1) {
      border-right: none;
    }
    .red {
      color: #f9607d;
      font-size: 18px;
    }
    .blue {
      color: #01aaef;
      font-size: 18px;
    }
  }
}
// .BDname{
//   width: 20%;
// }
</style>